package com.wms.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.wms.entity.StorePurchase; // 采购入库实体类
import com.wms.service.StorePurchaseService; // 采购入库服务接口
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author TianWenHe
 * @date 2025/5/6
 * @desc Excel导入监听器 - 处理 StorePurchase 数据（采购入库）
 */
@Slf4j
public class StorePurchaseListener extends AnalysisEventListener<StorePurchase> {

    // 批量插入阈值
    private static final int BATCH_COUNT = 5;

    // 缓存待插入数据
    private List<StorePurchase> storePurchases = new ArrayList<>();

    // 注入业务服务
    private StorePurchaseService storePurchaseService;

    public StorePurchaseListener(StorePurchaseService storePurchaseService) {
        this.storePurchaseService = storePurchaseService;
    }

    /**
     * 每解析一行数据会调用一次
     */
    @Override
    public void invoke(StorePurchase data, AnalysisContext context) {
        log.info("解析到一条采购入库单数据:{}", data);
        storePurchases.add(data);

        // 达到批处理数量时执行插入
        if (storePurchases.size() >= BATCH_COUNT) {
            saveData();
            storePurchases.clear();
        }
    }

    /**
     * 插入数据库的方法
     */
    private void saveData() {
        log.info("{}条采购入库单数据，开始存储数据库！", storePurchases.size());
        storePurchaseService.insertBatch(storePurchases);
        log.info("采购入库单数据存储数据库成功！");
    }

    /**
     * 所有数据解析完成后调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (!storePurchases.isEmpty()) {
            saveData();
        }
        log.info("所有采购入库单数据解析完成！");
    }
}
